package com.test.demo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.test.demo.mapper.UserMapper;
import com.test.demo.pojo.User;
import com.test.demo.util.RedisUtil;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 查询所有用户信息
     * @return List<User>
     */
    public List<User> qryUserList(){
        Object userInfoList = redisUtil.get("444");
        List<User> users = new ArrayList<>();
        if(Objects.isNull(userInfoList) ){
            users = userMapper.selectList();
            Object toJSON = JSONArray.toJSON(users);
            redisUtil.set("444",toJSON);
        }else {
            System.out.println("进入缓存");
            users = JSONArray.parseArray(userInfoList.toString()).toJavaList(User.class);
        }
        return users;
    }

    /**
     * 6通过id查询用户信息
     * @return
     */
    public void sendUserInfo(Long id) throws Exception {
        User infoById = userMapper.getInfoById(id);
        final String body = JSON.toJSONString(infoById);
        DefaultMQProducer defaultMQProducer = new DefaultMQProducer("rocket-test");
        //设置nameSrv地址和端口
        defaultMQProducer.setNamesrvAddr("192.168.254.129:9876");
        defaultMQProducer.setInstanceName("producer");
        //开启动生产者
        defaultMQProducer.start();
        //设置topic、tag 、消息体
        Message message = new Message("testTopic","testTag",body.getBytes());
        //设置延迟消息等级
        //发送消息
        defaultMQProducer.send(message);
        defaultMQProducer.shutdown();
    }

}
